import json
import urllib
# from util.lib.NET import NET
import hashlib
import time


class test:
    def __init__(self):
        self.token = ''
        self.run()

    def browser_get(self, url, data=None):
        _str = ''
        if data is not None:
            _str = '&'
            for key in data:
                _str += str(key) + '=' + str(data[key]) + '&'
            _str = _str[:-1]
        headers = {
            'Authorization': str(self.token),
        }
        print(url + _str)
        req = urllib.request.Request(url + _str, headers=headers)
        response = urllib.request.urlopen(req)
        res_str = response.read().decode('utf-8')
        return res_str

    def run(self):
        url = 'http://123.207.243.228/tao/?r=tao/'
        openId = 'open1'
        now = str(time.time())
        m2 = hashlib.md5()
        m2.update(('tao' + now).encode('utf-8'))
        # m2.update('tao' + now)
        sign = m2.hexdigest()
        res = self.browser_get(url + 'auth', {
            'openId': openId,
            'time': now,
            'sign': sign,
        })
        json_obj = json.loads(res)
        self.token = json_obj['token']

        # test
        res = self.browser_get(url + 'test')
        print(res)

        # active
        res = self.browser_get(url + 'active', {
            'deviceId': 'imei1'
        })
        print(res)

        # send
        res = self.browser_get(url + 'send', {
            'type': 1,
            'deviceId': 'imei2',
            'content': 'xxxxx'
        })
        print(res)

        # location
        res = self.browser_get(url + 'location', {
            'deviceId': 'imei2'
        })
        print(res)
        exit()
if __name__ is "__main__":
    test()